<template>
  <el-container>
    <div class="music-wrap">
      <audio id="audio" :src="musicSrc"></audio>
    </div>
    <div style="margin-top: 100px;display: flex;border-radius:40px ;">
      <el-aside width="200px" class="chat-list">
        <div class="search">
          <el-input class="search-input" size="mini" style="height: 10px; width: 100px" v-model="input"
            placeholder="搜索">
          </el-input>
          <img class="search-icon" src="../../public/images/搜素.png" />
        </div>
        <div v-if="(item.id != user.id && item.status == 1)" v-for="item in users"
          :class="item == currentChat ? 'chat-list-item chatActive' : 'chat-list-item'" :key="item.id"
          @click="chooseChat(item)">
          <template>
            <img class="avatar" :src="item.avatar" />
            <div class="chat-list-item-info">
              <span class="chat-list-item-name"> {{ item.nickName }}</span>
              <el-badge v-show="item.msgNum >= 1" :value="item.msgNum" :max="99" class="msg-tag">
              </el-badge>
              <div class="chat-list-item-text">{{ item.msg }}</div>
            </div>
          </template>
        </div>
      </el-aside>
      <el-container>
        <el-header style="font-size: 22px;"><span class="current-chat-name">{{ currentChat.nickName }}</span>
        </el-header>
        <el-main>
          <div class="chat-detail" v-for="msg in ChatDetail" :key="msg.id">
            <div :class="getTime(msg.createTime).length > 6 ? 'msg-time long-time' : 'msg-time'">{{ getTime(msg.createTime) }}</div>
            <div :class="user.id != msg.userId ? 'detail-u' : 'detail-me'">
              <img :src="msg.avatar" />
              <div class="detail-content">{{msg.msgText }}</div>
            </div>
          </div>
        </el-main>
        
        <div class="footer">
          <div class="chatIcon">
            <el-popover placement="top-start" width="400" trigger="click" class="emoBox">
              <div class="emotionList">
                <a href="javascript:void(0);" @click="getEmo(index)" v-for="(item, index) in faceList" :key="index"
                  class="emotionItem">{{ item }}</a>
              </div>
              <el-button class="emotionSelect"  slot="reference"></el-button>
            </el-popover>
          </div>
          <textarea  v-model="msgText"></textarea>
          <div class="sendMsg">
            <el-button @click="sendMsg">发送</el-button>
          </div>
        </div>
      </el-container>
    </div>
  </el-container>
</template>

<script>
let socket;
import UserCard from "./UserCard.vue";
import { getToken } from "@/utils/auth";
import { getInfo } from "@/api/user";
import Emoji from "@/utils/emoji.json";
import { timeFilter } from "@/utils/dateFormat";
export default {
  name: "CharWindow",
  components: { UserCard },
  data() {
    return {
      musicSrc: "/music/iphone.mp3",
      msg: "",
      input: "",
      currentChat: "",
      msgText: "",
      faceList: [],
      msgList: [],
      ChatDetail: [],
      users: [],
      user: {},
    };
  },
  created() {
    this.init();
  },
  mounted() {
    for (let i in Emoji) {
      this.faceList.push(Emoji[i].char);
    }
  },
  updateed() {
    this.users = [];
    this.msgList = [];
    this.init();
  },
  watch: {
    users: {
      handler(newVal, oldVal) {
        console.log("watch the users ===> ", newVal, oldVal);
      },
      deep: true,
    },
  },
  methods: {
    getTime(t) {
      return timeFilter(t);
    },
    //获取表情
    getEmo(index) {
      this.msgText = this.msgText + this.faceList[index];
    },
    // 播放音乐
    musicPlay(music) {
      // let rec = "https://api.xmj123.top:8888/down/P3eg738RoCWK.mp3";
      // let send = "https://api.xmj123.top:8888/down/VeQ6d4MjLnGH.mp3";
      let rec = "/music/iphone.mp3";
      let send = "/music/send.mp3";
      if (music == "send") {
        this.musicSrc = send;
      } else {
        this.musicSrc = rec;
      }
      const audio = document.getElementById("audio");
      audio.play();
    },
    // 选择聊天对象
    chooseChat(u) {
      if (u.msgNum) u.msgNum = 0;
      this.currentChat = u;
      this.ChatDetail = [];
      let _this = this;
      this.msgList.forEach(item => {
        if (u.id == item.userId || u.id == item.receiverId) {
          _this.ChatDetail.push(item);
        }
      });
    },
    // 发送消息
    sendMsg() {
      let _this = this;
      if (!this.currentChat) {
        this.$message({ type: "warning", message: "请选择聊天对象" });
        return;
      }
      if (!this.msgText) {
        this.$message({ type: "warning", message: "请输入内容" });
      } else {
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          let message = {
            receiverId: _this.currentChat.id,
            userId: _this.user.id,
            avatar: _this.user.avatar,
            createTime: new Date(),
            nickName: _this.user.nickName,
            avatar: _this.user.avatar,
            msgText: _this.msgText,
          };
          _this.msgList.push(message);
          socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
          // 构建消息内容，本人消息
          _this.msgText = "";
          _this.ChatDetail.push(message);
          _this.musicPlay("send");
        }
      }
    },
    // 初始化
    init() {
      let _this = this;
      let token = getToken();
      if (_this.user == null || _this.user.id == null) {
        getInfo(token).then(res => {
          console.log("获取个人信息res.data===>", res.data);
          if (res.code == 200) {
            _this.user = res.data;
            _this.socketConnect();
          } else {
            _this.$message({ type: "error", message: res.msg });
          }
        });
      } else {
        _this.socketConnect();
      }
    },
    // socket连接
    socketConnect() {
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8088/websocket/" + _this.user.id;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function() {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function(msg) {
          let data = JSON.parse(decodeURIComponent(msg.data));
          if (data.users) {
            // console.log("用户数据===>");
            _this.users = data.users;
            _this.msgList = data.msgList;
            if (data.msgList) {
              console.log("聊天记录===>", data.msgList);
              _this.msgList = data.msgList;
            }
          } else {
            _this.musicPlay("rec");
            // console.log("消息===>", data);
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            _this.msgList.push(data);
            _this.users.forEach(item => {
              if (item.id == data.userId) {
                item["msgNum"] = item.msgNum == null ? 1 : item.msgNum + 1;
              }
            });
            if (_this.currentChat.id == data.userId) {
              _this.ChatDetail.push(data);
            }
            console.log("接收到了消息====>", data);
          }
        };
        //关闭事件
        socket.onclose = function() {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
          console.log("websocket发生了错误");
        };
      }
    },
  },
};
</script>

<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "黑体";
  max-height: 588px;
}

textarea {
  width: 680px;
  margin-top: 35px;
  font-size: 18px;
  height: 120px;
  outline: none;
  resize: none;
  border: none;
  background: transparent;
  -webkit-tap-highlight-color: rgba(255, 0, 0, 0);
  -webkit-appearance: none; //是为了去除内阴影样式，但是缺点是不可输入；
  -webkit-user-select: auto; // 解决输入问题；
}

.myavatar {
  width: 50px;
  height: 80px;
  padding: 5px;

  img {
    margin-top: 30px;
    width: 40px;
    height: 40px;
  }
}

.setting::-webkit-scrollbar {
  display: none;
}

* {
  scrollbar-width: none;
}

.setting-list {
  width: 50px;
}

.setting-list-item {
  // background: red;
  width: 35px;
  height: 35px;
  padding: 12px;

  img {
    width: 35px;
    height: 35px;
  }
}

.a {
  background: #c5c4c4;
}

.el-header {
  width: 700px;
  background: #f7f7f7;
  border-bottom: 1px solid rgba(38, 35, 53, 0.1);
  color: #333;
  text-align: center;
  line-height: 60px;
  text-align: left;
  position: relative;

  .current-chat-name {
    margin-left: 25px;
  }

  .online-img {
    position: absolute;
    width: 20px;
    height: 20px;
    left: 160px;
    bottom: 5px;

    img {
      width: 10px;
      height: 10px;
    }
  }
}

.msg-tag {
  margin-right: -10px;
  float: right;
}

.footer {
  width: 700px;
  border-top: 1px solid rgba(38, 35, 53, 0.1);
  background: #f5f5f5;
  color: #333;
  text-align: center;
  line-height: 60px;
  height: 210px;
  position: relative;
}

.sendMsg {
  position: absolute;
  bottom: 0;
  right: 50px;

  .el-button {
    height: 30px;
    width: 60px;
    font-size: 15px;
    color: #2cda71;
    background: #e9e9e9;
    padding: 2px;
  }
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  //   line-height: 200px;
  max-height: 600px;
  overflow-x: hidden;
  overflow-y: scroll;
  height: 600px;
  width: 230px;
  background: rgba(231, 231, 231, 1);
}

.right {
  // position: absolute;
  // right: 0;
  margin-right: 20px;
  float: right;
  display: inline-block;
  widows: 100%;
}

.float-right {
  float: right;
}

.el-main {
  height: 300px;
  width: 700px;
  background: #f5f5f5;
  color: #333;
  text-align: center;
  // line-height: 160px;
  overflow-x: hidden;
  overflow-y: scroll;
  display: inline-block;
  position: relative;

  .chat-detail {
    width: 700px;
    // background: grey;
    margin-top: 40px;
    margin-bottom: 30px;
    display: flex;
    position: relative;
    min-height: 50px;
    font-size: 18px;
    max-height: 500px;
    .msg-time {
      font-size: 15px;
      width: auto;
      height: 10px;
      position: absolute;
      top: -30px;
      left: 320px;
      padding: 10px;
      display: block;
      background: #dadada;
      color: white;
      line-height: 10px;
    }

    .long-time {
      left: 260px;
    }

    .detail-me {
      margin-top: 10px;
      margin-right: 20px;
      width: 100%;
      right: 0;

      img {
        float: right;
        width: 40px;
        height: 40px;
      }

      .detail-content {
        margin-right: 10px;
        margin-top: 3px;
        float: right;
        min-height: 28px;
        padding: 6px;
        max-width: 280px;
        max-height: 355px;
        background: #95ec69;
        border-radius: 5px;
        text-align: right;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 15;
        text-overflow: ellipsis;
        word-break: break-all;
        overflow: hidden;
      }
    }

    .detail-u {
      margin-top: 10px;
      width: 100%;
      margin-left: 20px;

      img {
        float: left;
        width: 40px;
        height: 40px;
      }

      .detail-content {
        margin-left: 10px;
        margin-top: 3px;
        float: left;
        min-height: 28px;
        padding: 6px;
        max-width: 280px;
        background: #ffffff;
        border-radius: 5px;
        text-align: left;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 15;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
}

ul li {
  list-style: none;
}

.el-main::-webkit-scrollbar {
  display: none;
}

::v-deep .el-input {
  width: 150px !important;
  height: 10px !important;
  background: #e2e2e2 !important;
}

.search {
  width: 230px;
  min-height: 50px;
  padding-top: 5px;
  //   background: red;
  //   background: #f7f7f7;
  display: flex;

  .search-input {
    width: 300px;
    height: 20px;
    margin-left: 10px;
    margin-top: 10px;
    // background: blue;
    background: #e2e2e2 !important;
  }

  .search-icon {
    width: 20px;
    // background: red;
    margin-top: 15px;
    margin-left: 8px;
    height: 20px;

    .search-icon img {
      padding-top: 20px;
      padding: 5px;
    }
  }
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.user-item {
  height: 50px;
}

.chat-list::-webkit-scrollbar {
  display: none;
}

// .chat-list::-webkit-scrollbar {
//   height: 10px !important;
//   width: 4px;
// }

// .chat-list::-webkit-scrollbar-track {
//   -webkit-box-shadow: inset 0 0 5px transparent;
//   border-radius: 10px;
// }

// .chat-list::-webkit-scrollbar-thumb {
//   width: 4px;
//   height: 10px;
//   background: rgba(128, 128, 128, 0.3);
// }
.chat-list-item {
  width: 230px;
  height: 60px;
  display: flex;
  position: relative;

  //   border-bottom: solid 1px #333;
  .avatar {
    padding: 5px;
    width: 50px;
    height: 50px;
    border-radius: 10px;
  }

  .chat-list-item-info {
    width: 120px;

    // background: rgba(255, 0, 0, 0.4);
    .chat-list-item-name {
      float: left;
      text-align: left;
      width: 120px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      height: 25px;
      font-size: 15px;
      padding: 5px;
      //   display: block;
      //   margin-left: -50px;
    }

    .chat-list-item-text {
      float: left;
      padding-left: 5px;
      width: 120px;
      overflow: hidden;
      white-space: nowrap;
      text-align: left;
      text-overflow: ellipsis;
      height: 20px;
      color: rgba(5, 8, 9, 0.4);
      padding-bottom: 2px;
      //   background: blue;
      font-size: 12px;
    }
  }
}

.chatActive {
  background: #cdcdcc;
}

.chat-list-item:hover {
  background: rgba(209, 208, 208, 0.6);
}

.chatIcon {
  position: absolute;
  top: 0;
  left: 0;
  width: 30px;
  height: 30px;
  padding: 10px;
  font-size: 25px;
}

.emotionSelect {
  background: transparent;
  border: none;
  top: 0px;
  left: 10px;
  position: absolute;
  width: 30px;
  height: 30px;
  background-image: url("../../public/images/表情包.png");
  background-size: cover;
}

.emotionList {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
}
.emotionItem {
  width: 10%;
  font-size: 20px;
  text-align: center;
}
/*包含以下四种的链接*/
.emotionItem {
  text-decoration: none;
}
/*正常的未被访问过的链接*/
.emotionItem:link {
  text-decoration: none;
}
/*已经访问过的链接*/
.emotionItem:visited {
  text-decoration: none;
}
/*鼠标划过(停留)的链接*/
.emotionItem:hover {
  text-decoration: none;
}
/* 正在点击的链接*/
.emotionItem:active {
  text-decoration: none;
}
</style>
